 AddCSLuaFile("cl_init.lua")
 AddCSLuaFile("shared.lua")

 include("shared.lua")
  
ENT.ObjectTouching = false

function ENT:Initialize()
	self.Entity:SetModel("models/props_c17/oildrum001.mdl")
	self.Entity:SetMoveType(MOVETYPE_NONE)
	self.Entity:SetSolid(SOLID_NONE)
	self.Entity:DrawShadow( false )
	return true
end

function ENT:Think()
	for _,ent in pairs( ents.GetAll() )do
		if ValidEntity(ent) && ent:Health() > 0 then
			if ent:GetPos():Distance(self.Entity:GetPos()) > 100 then
				self.ObjectTouching = false
			else
				self.ObjectTouching = true
			end
		end
	end
	if (!self.ObjectTouching) then
		local tblWaveTable = WaveTable(GAMEMODE.OnWave)
		local tblNPCTable = NPCTable(table.Random(tblWaveTable.NPCs))
		if (!tblWaveTable.SpawnedNPCs) then tblWaveTable.SpawnedNPCs = 0 end
		if (!tblWaveTable.TotalNPCs) then tblWaveTable.TotalNPCs = 0 end
		if (tblWaveTable.SpawnedNPCs < tblWaveTable.MaxNPCs && ( !tblWaveTable.MaxTotalNPCs || tblWaveTable.TotalNPCs < tblWaveTable.MaxTotalNPCs ) ) then
			if (!self.Entity.NextSpawn) then self.Entity.NextSpawn = CurTime() + (tblNPCTable.SpawnTime + math.random(1,10)) end
			if (tblNPCTable.SpawnTime > 0 && CurTime() >= self.Entity.NextSpawn) then
				self:CreateNPC(tblNPCTable)
				tblWaveTable.SpawnedNPCs =  tblWaveTable.SpawnedNPCs + 1
				tblWaveTable.TotalNPCs =  tblWaveTable.TotalNPCs + 1
				print(tblWaveTable.TotalNPCs)
				self.Entity.NextSpawn = nil
			end
		end
	end
end

function ENT:CreateNPC(NPCTable)
	local entNewNPC = ents.Create(NPCTable.Class)
	entNewNPC:SetPos(self.Entity:GetPos() + Vector(0,0,NPCTable.SpawnOffsetz or 0))
	entNewNPC:Spawn()
	entNewNPC.Name = NPCTable.Name
	entNewNPC.Level = GAMEMODE.OnWave * NPCTable.Level or 1
	entNewNPC:SetNWString("Name", entNewNPC.Name)
	entNewNPC:SetNWInt("Level", entNewNPC.Level)
	for _, ent in pairs(ents.GetAll()) do
		if (ent && ent:IsValid()) then
			if  (ent:IsNPC()) then
				entNewNPC:AddEntityRelationship(ent, D_LI, 99)
				ent:AddEntityRelationship(entNewNPC, D_LI, 99)
			end
			if (ent:IsPlayer()) then
				entNewNPC:AddEntityRelationship(ent, D_HT, 99)
				entNewNPC:SetLastPosition( ent:GetPos() )
				entNewNPC:SetSchedule( SCHED_FORCED_GO ) 
				entNewNPC:SetNPCState( NPC_STATE_COMBAT )
				entNewNPC:SetEnemy( ent )
			end
		end
	end
	--entNewNPC:AddRelationship("player D_LI 99")
end
